import {
	Toast
} from "vant"
let needLoadingRequestCount = 0;
let timer;
let loadingService = null;

function startLoading(loadingText="Loading") {
	loadingService = Toast.loading({
        message: loadingText,
        forbidClick: true,
        loadingType: 'spinner'
    });
}

function endLoading() {
	loadingService.clear();
    loadingService = null;
}

const tryCloseLoading = () => {
	if (needLoadingRequestCount === 0) {
		endLoading()
	}
}

export function showLoading(loadingText) {
	if (timer) {
		clearTimeout(timer)
		timer = null;
	}
	if (needLoadingRequestCount === 0 && !loadingService) {
		startLoading(loadingText)
	}
	needLoadingRequestCount++;
}

export function hideLoading() {
	if (needLoadingRequestCount <= 0) {
		return;
	}
	needLoadingRequestCount--;
	if (needLoadingRequestCount === 0) {
		tryCloseLoading()
	}
}
